package com.guoxin.artconcurrency.chapter4;

import java.util.concurrent.TimeUnit;

public class PolitelyStop {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new Runner(), "CountThread");
        t1.start();
        TimeUnit.SECONDS.sleep(2);
        t1.interrupt();

        Runner r = new Runner();
        Thread t2 = new Thread(r, "CountThread");
        t2.start();
        TimeUnit.SECONDS.sleep(2);
        r.shutdown();
    }

    private static class Runner implements Runnable {
        private int i;
        private volatile boolean isAlive = true;

        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted() && isAlive) {
                i++;
            }
            System.out.println("Counte i= " + i);
        }

        private void shutdown() {
            this.isAlive = false;
        }
    }
}
